<?php

namespace application\extensions;

use Exception;

class AuthInterceptor implements \core\system\AuthInterceptor\Interceptor {

    public static function authentic() {
        $core = new \core\CoreBase();
        $session = new \core\system\Session();
        $uri = $_SERVER['REQUEST_URI'];
        
        
        if (strpos($uri, "auth/signout") || strpos($uri, "auth/signin")) {
            return true;
        }
        
        if ($session->administrator == null) {
            \core\system\HttpResponse::redirect($core->baseUrl . 'cp/auth/signin.html');
            return false;
        }


        if ($session->administrator != null && strpos($uri, "/auth/signin")) {
            \core\system\HttpResponse::redirect($core->baseUrl . 'cp/index.html');
            return false;
        }

        if ($session->administrator != null && strpos($uri, "cp/index.html")) {
            return true;
        }
        $func = "";
        if (strpos($uri, ".html")) {
            $uri = explode("/cp", $uri);
            $func = "cp" . $uri[1];
        } else {
            $uri = explode("/cpservice", $uri);
            $func = "cpservice" . $uri[1];
        }

        $function = new \application\service\FunctionService();
        $func = $function->getFunctionByUri($func);
        if ($func->id == null || !in_array($func->id, $session->administratorRole)) {
            if ($func->type == null || $func->type == 1) {
                \core\system\HttpResponse::redirect($core->baseUrl . 'cp/index.html');
            } else {
                throw new Exception("Bạn không có quyền thực hiện chức năng này");
            }
            return false;
        }

        return true;
    }

}
